﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using Streambolics.Gui;

namespace Streambolics.Hp41s.Gui
{
    public partial class EngineUserControl : TransparentUserControl
    {
        private Engine _Machine;

        public EngineUserControl ()
        {
            InitializeComponent ();
        }

        protected virtual void OnDisplayChanged (EventArgs e)
        {
        }

        void _Machine_DisplayChanged (object sender, EventArgs e)
        {
            OnDisplayChanged (e);
        }

        protected virtual void Link (Engine aEngine)
        {
            aEngine.DisplayChanged += new EventHandler (_Machine_DisplayChanged);
            _Machine_DisplayChanged (this, EventArgs.Empty);
        }

        protected virtual void Unlink (Engine aEngine)
        {
            aEngine.DisplayChanged -= new EventHandler (_Machine_DisplayChanged);
        }

        [Browsable (false)]
        public Engine Machine
        {
            get
            {
                return _Machine;
            }
            set
            {
                if (value != _Machine)
                {
                    if (_Machine != null) Unlink (_Machine);
                    _Machine = value;
                    if (_Machine != null) Link (_Machine);
                }
            }
        }

        protected override void OnDisposing (EventArgs e)
        {
            base.OnDisposing (e);
            Machine = null;
        }

        protected Instruction GetInstruction (DragEventArgs aDragDrop)
        {
            if (_Machine == null)
            {
                return null;
            }
            Data d = DragData.GetDragData<Data> (aDragDrop, this);
            if (d == null)
            {
                return null;
            }
            return d.ToInstruction ();
        }

        protected override void OnDragDrop (DragEventArgs drgevent)
        {
            base.OnDragDrop (drgevent);
            Instruction i = GetInstruction (drgevent);
            if (i != null)
            {
                _Machine.Execute (i);
            }
        }

        protected override void OnDragEnter (DragEventArgs drgevent)
        {
            base.OnDragEnter (drgevent);
            if (GetInstruction (drgevent) != null)
            {
                drgevent.Effect = DragDropEffects.Copy;
            }
        }

    }
}
